package com.huluobo.high3demo.login;

import android.app.Application;

import androidx.annotation.NonNull;
import androidx.lifecycle.MutableLiveData;

import com.google.gson.Gson;
import com.huluobo.mvvm.baen.UserBeanResult;
import com.huluobo.mvvm.db.eneity.Money;
import com.huluobo.mvvm.db.eneity.UserInfo;
import com.huluobo.mvvm.net.Constant;
import com.huluobo.mvvm.viewmodel.BaseViewModel;

import java.util.HashMap;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * Created by LC on 2023/9/14.
 */
public class LoginViewModel extends BaseViewModel<LoginRepo> {
    MutableLiveData<UserBeanResult.UserBean> loginSuccess = new MutableLiveData<>();
    MutableLiveData<String> loginFailed = new MutableLiveData<>();

    public LoginViewModel(@NonNull Application application) {
        super(application);
    }

    public void login(String username, String password) {
        repo.login(username, password, loginSuccess, loginFailed);
        //model.login(username,password)
    }

    public void loginJson(String username, String password) {
        //封装参数
        Map<String, String> map = new HashMap<>();
        map.put(Constant.PARAM_USERNAME, username);//键值对形式
        map.put(Constant.PARAM_PASSWORD, password);

        String json = new Gson().toJson(map);//把map转化为一个json
        RequestBody body = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), json);//把json转换为一个body
        repo.loginJson(body, loginSuccess, loginFailed);
    }

    public void saveUserInfo(UserBeanResult.UserBean userBean) {
        //把Bean转换为一个userInfo
        UserInfo userInfo = new UserInfo();
        userInfo.userId = userBean.getId();
        userInfo.username = userBean.getUsername();
        userInfo.icon = userBean.getIcon();
        repo.saveUserToDatabase(userInfo);
    }


    public void insertUserMoney(String username, float money) {
        Money entity = new Money(username, money);
        repo.insertUserMoney(entity);
    }

    //new 了一个Repo出来,相当于new了一个model层
    @Override
    protected LoginRepo createRepo() {
        return new LoginRepo();
    }
}
